#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@ author:konnlee
@ time  :2020/5/11 19:46
@ School:BESTI
"""
import socket
import json
import struct
import hashlib
from my_des_c import des_decrypt


if __name__ == "__main__":

    server = socket.socket()
    server.bind(("127.0.0.1", 8001))
    server.listen(5)
    print("Server is working……\n",
          "\tWaiting for connect……")

    while True:
        conn, address = server.accept()
        print("客户端连接成功，客户端IP地址:", address[0])
        try:
            while True:
                len_header = conn.recv(4)
                try:
                    res = struct.unpack("i", len_header)
                except:
                    print("客户端通过 exit 命令正常断开了本次连接")
                    break
                info_header = conn.recv(res[0])
                header = json.loads(info_header)

                action = header.get("action")
                filename = header.get("filename")
                filesize = header.get("filesize")

                print(">>> ", address[0], action, filename, "文件大小：", filesize / 1000, "kb")
                if action == "put":
                    # 接受文件数据
                    md5 = hashlib.md5()
                    with open(filename, 'wb') as f:
                        recv_data_len = 0
                        while recv_data_len < filesize:
                            data = conn.recv(1024)
                            data_dealed = des_decrypt(data)
                            recv_data_len += len(data_dealed)
                            f.write(data_dealed)
                            md5.update(data_dealed)

                    print("文件接受成功".center(50, '*'))
                    conn.send("\n服务器接受成功,正在验证文件完整性……".encode())
                    recv_md5: str = conn.recv(1024).decode()
                    if md5.hexdigest() == recv_md5:
                        print("文件完整性验证通过")
                        print('*' * 50)
                        conn.send("文件完整性验证通过".encode())
                    else:
                        print("文件完整性验证失败，发送过程中文件可能丢失或被篡改！！！")
                        print('*'*50)
                        conn.send("文件完整性验证失败，发送过程中文件可能丢失或被篡改！！！".encode())

        except Exception as e:
            print("客户端意外退出！{错误码：", e.args[0], "\t错误原因：", e.args[1], "}\n", '*'*80)
